package com.dianganjiao.lib.work

import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import com.dianganjiao.lib.AppContext
import com.dianganjiao.lib.life.ViewModelQuick
import com.dianganjiao.lib.util.Loog
import java.util.*

class Works {

    private var mWorkPosition = 0
    private val works = arrayListOf<Any>()
    private var key:String = UUID.randomUUID().toString() + System.currentTimeMillis().toString()
    internal var stopWork = false

    private constructor()


    companion object {

        fun newBuilder(): Builder {
            return Builder(Works())
        }
    }

    /**
     * 开始执行任务
     * @param lifeOwner 任务的生命周期提供者
     */
    fun queue(lifeOwner: AppCompatActivity) {
        if (works.isNotEmpty()) {
            bindLifeOwnerToTask(lifeOwner)
            Work.addWork(key,this)
            mWorkPosition = -1
            doWork(lifeOwner)//执行第一个任务
        }
    }

    /**
     * 当前activity作为默认的生命周期提供者
     */
    fun queue(){
        if (works.isNotEmpty()) {
            val lifeOwner = AppContext.appContext.getCurrentActivity()
            if(lifeOwner != null && lifeOwner is AppCompatActivity) {
              queue(lifeOwner)
            }
        }
    }

    /**
     * 先绑定生命周期并初始化
     */
    private fun bindLifeOwnerToTask(lifeOwner: AppCompatActivity) {
        works.forEach {
            if (it is Task<*>) {
                val args = arrayListOf<Any>()
                args.add(lifeOwner)
                args.add(key)
                args.addAll(it.getArgs().toList())
                ViewModelQuick.observer(lifeOwner, it.getWork(), *args.toTypedArray())
            }
        }
    }

    /**
     * 执行
     */
    internal fun doWork(lifeOwner: AppCompatActivity, vararg args: Any) {
        if (stopWork) {
            Loog.e("任务已被停止")
            return
        }

        onWorkCurrentResult(lifeOwner, *args)

        mWorkPosition++

        if (!isEnd()) {
            if (works[mWorkPosition] is Task<*>) {
                val task = works[mWorkPosition] as Task<*>
                ViewModelQuick.get(lifeOwner, task.getWork()).mOnWorkCallback?.onWorkStart(*args)
                ViewModelQuick.get(lifeOwner, task.getWork()).doWork(*args)
            }
        }
    }

    /**
     * 回调当前任务完成
     */
    private fun onWorkCurrentResult(lifeOwner: AppCompatActivity, vararg args: Any){
        if (!isEnd() && mWorkPosition != -1) {
            if (works[mWorkPosition] is Task<*>) {
                val task = works[mWorkPosition] as Task<*>
                ViewModelQuick.get(lifeOwner, task.getWork()).mOnWorkCallback?.onWorkResult(*args)
            }
        }
    }

    /**
     * 找到并执行一个任务
     */
    internal fun <W:AbsWork> findWorkToDo(work: Class<W>,lifeOwner: AppCompatActivity,vararg args:Any):Boolean{
        onWorkCurrentResult(lifeOwner, *args)
        var i = 0
        works.forEach {
            if (it is Task<*>) {
                if(TextUtils.equals(it.getWork().name,work.name)){
                    mWorkPosition = i
                    ViewModelQuick.get(lifeOwner, it.getWork()).mOnWorkCallback?.onWorkStart(*args)
                    ViewModelQuick.get(lifeOwner, it.getWork()).doWork(*args)
                    return true
                }
                i++
            }
        }
        return false
    }

    /**
     * 重新开始任务
     */
    internal fun reStartWork(lifeOwner: AppCompatActivity,vararg args:Any){
        onWorkCurrentResult(lifeOwner, *args)
        mWorkPosition = -1
        doWork(lifeOwner,*args)
    }

    /**
     * 重新执行一个任务
     */
    internal fun retryWork(lifeOwner: AppCompatActivity, vararg args: Any){
        if (stopWork) {
            Loog.e("任务已被停止")
            return
        }
        onWorkCurrentResult(lifeOwner, *args)
        if (!isEnd()) {
            if (works[mWorkPosition] is Task<*>) {
                val task = works[mWorkPosition] as Task<*>
                ViewModelQuick.get(lifeOwner, task.getWork()).mOnWorkCallback?.onWorkStart(*args)
                ViewModelQuick.get(lifeOwner, task.getWork()).doWork(*args)
            }
        }
    }

    /**
     * 是否结束
     */
    private fun isEnd(): Boolean {
        return works.size <= mWorkPosition
    }

    /**
     * 设置builder
     */
    private fun setWorks(works: List<Any>) {
        this.works.clear()
        this.works.addAll(works)
    }

    class Builder {
        private val works = arrayListOf<Any>()
        private var mWorks: Works

        constructor(mWorks: Works) {
            this.mWorks = mWorks
            works.clear()
        }

        /**
         * 添加一个任务
         */
        fun <w : AbsWork> add(work: Class<w>, vararg args: Any): Builder {
            works.add(Task(work, *args))
            return this
        }


        /**
         * 添加另一个任务池
         */
        fun add(builder: Builder): Builder {
            works.addAll(builder.works)
            return this
        }

        /**
         * 构建Work
         */
        fun build(): Works {
            mWorks.setWorks(works)
            return mWorks
        }

    }

    private class Task<W : AbsWork> {
        private var w: Class<W>
        private val args = arrayListOf<Any>()

        constructor(w: Class<W>, vararg args: Any) {
            this.w = w
            this.args.clear()
            this.args.addAll(args.toList())
        }

        fun getWork(): Class<W> {
            return w
        }

        fun getArgs(): List<Any> {
            return args
        }

    }
}